package com.cscp.javastudy.juc.cas;

import java.util.concurrent.atomic.AtomicInteger;

/**
 * CAS: Compare and Swap
 */
public class CASDemo1 {

    public static void main(String[] args) {
        AtomicInteger atomicInteger = new AtomicInteger(2020);
        /*
         * public final boolean compareAndSet(int expect, int update)
         * expect: 期望的值
         * update: 要更新的新值
         * 如果是期望的值则更新，否则不更新
         */

        System.out.println(atomicInteger.compareAndSet(2020, 2021));//期望值是2020，所以修改为2021，返回true
        System.out.println(atomicInteger.get());//2021

        System.out.println(atomicInteger.compareAndSet(2020, 2022));//期望是2020，但实际是2021，所以无法修改值为2022，返回false
        System.out.println(atomicInteger.get());//2021
    }
}
